﻿(function ($) {
	var $modal = null;
	function show(modalOptions) {
		var options = $.extend({}, defaultOptions, modalOptions);
		
		$modal = $('#' + options.modalId);

		var $headerBlock = $('div.modal-header', $modal);
		var $applyBtn = $('a[data-type="apply"]', $modal);
		var $cancelBtn = $('a[data-type="cancel"]', $modal);
		var $header = $('h4', $headerBlock);
		var $body = $('div.modal-body', $modal);

		if (options.showCancelBtn != null && !options.showCancelBtn) {
			$cancelBtn.hide();
		} else {
			$cancelBtn.show();
		}

		$applyBtn.text(options.applyBtnName).show();

		if (options.header != null) {
			$header.text(options.header);
			$headerBlock.show();
		} else {
			$headerBlock.hide();
		}

		if (options.body instanceof jQuery) {
			$body.empty().append(options.body);
		} else {
			$body.empty().append($('<div/>').append(options.body));
		}

		$applyBtn.unbind('click');
		$applyBtn.bind('click', function (e) {
			e.preventDefault();
			if (options.applyFunc != null) {
				options.applyFunc(options.applyObj);
			}
			
			if (options.closeOnApply)
				$modal.modal('hide');
		});

		//options.fullScreen = true;

		$modal.unbind('shown');
		$modal.bind('shown', function () {
			if (options.fullScreen) {
				$('div.modal-body', $modal).css('max-height', '1000px');
				$modal.css('top', '0%');
				$modal.css('left', '0%');
				$modal.css('width', '100%');
				$modal.css('height', '100%');
				$modal.css('margin', '0');
			} /*else {
				$modal.css('top', '50%');
				$modal.css('left', '50%');
				$modal.css('width', '560px');
				//$modal.css('height', '100%');
				$modal.css('margin', '-250px 0 0 -280px');
			}*/
		});

		$modal.unbind('hide');
		if (options.onHideModal != null) {
			$modal.bind('hide', options.onHideModal);
		}

		$modal.modal({
			backdrop: options.modalBackdrop, //true
			show: true,
			keyboard: options.modalKeyboard,
			remote: options.modalRemote,
		});


/*		if (options.fullScreen) {
			$modal.css('top', '0% !important');
			$modal.css('left', '0% !important');
			$modal.css('width', '100% !important');
			$modal.css('height', '100% !important');
			$modal.css('margin', '0 !important');
		} else {
			$modal.css('top', '50%');
			$modal.css('left', '50%');
			$modal.css('width', '560px');
			//$modal.css('height', '100%');
			$modal.css('margin', '-250px 0 0 -280px');
		}*/

		return $modal;
	}

	function close() {
		if ($modal != null)
			$modal.modal('hide');
	}

/*
*	$.SmarlyModal.show({});
*/

	var defaultOptions = {
		modalId: 'customModal',
		header: null,
		body: '',
		showCancelBtn: true,
		applyBtnName: 'Применить',
		applyFunc: null,
		applyObj: null,
		closeOnApply: true,
		
		modalBackdrop: 'static',
		modalKeyboard: true,
		modalRemote: false,
		fullScreen: false,
		
		onHideModal: null,
	};

	$.extend({
		SmarlyModal: {
			show: show
		}
	});
})(jQuery);